package com.example.controller;

import com.example.common.SessionCons;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2019/3/20
 * @Description: 类描述
 **/
@Controller
public class UserController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/login")
    @ResponseBody
    public String login(HttpServletRequest request, String username, String password) throws Exception {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        // 执行认证登陆
        try {
            subject.login(usernamePasswordToken);
            //将信息放入到session中
            //TODO：要考虑分布式的会话
//            subject.getSession().setAttribute(SessionCons.LOGIN_USER_SESSION,usernamePasswordToken);
//            subject.getSession().setAttribute(SessionCons.DEVICE_TYPE, "PC");
//            subject.getSession().setAttribute(SessionCons.LOGIN_USER_PERMISSIONS);
        } catch (UnknownAccountException e) {
            throw new Exception("账户错误");
        } catch (DisabledAccountException e) {
            throw new Exception("账户被锁定");
        } catch (IncorrectCredentialsException e) {
            throw new Exception("密码错误");
        }
        return "success";
    }


    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        System.out.println("test");
        redisTemplate.opsForValue().set("test", "test");
        return "test";
    }
}
